const koa = require('koa');
const router = require('./routes/router');
const bodyParser = require('koa-bodyparser');
const cors = require('koa2-cors');
const _ = require('underscore');
const app = new koa();
const server = require('http').createServer(app.callback());
const setMessage = require('./utils/setMessage')
const getMessage = require('./utils/getMessage')
const io = require('socket.io')(server, {
  cors: true,
  connectionStateRecovery: {
    // the backup duration of the sessions and the packets
    maxDisconnectionDuration: 1 * 60 * 1000,
    // whether to skip middlewares upon successful recovery
    skipMiddlewares: true,
  }

})
app.use(cors());
app.use(bodyParser());
app.use(router.routes()).use(router.allowedMethods())
let socketList = new Map()

io.on('connection', socket => {
  socket.on('login', async (data) => {
    if (!Object.keys(data).length) {
      return
    }
    if (!socketList.has(data.id)) {
      socketList.set(data.id, socket)
    }
    const result = await getMessage(data.id)
    if (result.length) {
      socket.emit("messageList", result)
    }
  })

  socket.on("receive", (info) => {
    console.log('接收到消息', info);
    if (socketList.has(info.receiverId)) {
      let s = socketList.get(info.receiverId)
      if (s.connected) {
        s.emit("message", info)
        setMessage(info)
      } else {
        console.log('离线消息', info);
        setMessage(info)
      }
    } else {
      setMessage(info)
    }
    /* for (const item of socketList) {
      if (item[0] == info.receiverId) {
        if (item[1].connected) {
          item[1].emit('message', info)
        }else{
          console.log('短线了');
          setMessage(info)
        }
        break;
      }
    } */

    // socket.on方法,服务端监听客户端emit的事件，事件名字为 "receive", 并且接收客户端发送过来的信息
  })
  socket.on('disconnect', () => {
    console.log('disconnect');
  })

})

server.listen(3000, () => {
  console.log('服务端已启动在http://localhost:3000');
})

